package com.dy.lock.screen.component.impl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;

import com.dy.lock.screen.component.MerchantAddressComponent;
import com.dy.lock.screen.constants.TransmissionCode;
import com.dy.lock.screen.exception.ServerDisponseException;
import com.dy.lock.screen.pojo.GoodsInfo;
import com.dy.lock.screen.pojo.MerchantAddress;
import com.dy.lock.screen.scoket.Head;
import com.dy.lock.screen.service.GoodsService;
import com.dy.lock.screen.service.MerchantAddressService;
import com.dy.lock.screen.utils.CommonUtil;
import com.dy.lock.screen.vo.MerchantAddressVo;
import com.dy.lock.screen.vo.MerchantResultVo;
import com.google.gson.Gson;

@Component("merchantAddressComponent")
public class MerchantAddressComponentImpl implements MerchantAddressComponent {
	private static final Logger log = Logger
			.getLogger(MerchantAddressComponentImpl.class);
	private Gson gson;

	@Resource(name = "merchantAddressService")
	private MerchantAddressService merchantAddressService;
	@Resource(name = "goodsService")
	private GoodsService goodsService;

	public MerchantAddressComponentImpl() {
		gson = CommonUtil.gson();
	}

	@Override
	public MerchantResultVo getNearestMerchantAddress(String body, Head head) {
		MerchantAddressVo vo = gson.fromJson(body, MerchantAddressVo.class);
		if (vo != null && StringUtils.isNotBlank(vo.getGoodsId())
				&& vo.getLat() > 0 && vo.getLng() > 0) {
			MerchantResultVo merResVo = new MerchantResultVo();
			GoodsInfo g = this.goodsService.queryByPrimaryKey(vo.getGoodsId());
			Integer totalcount = this.merchantAddressService
					.queryCountByMerchantId(g.getMerchantId(), head);
			merResVo.setTotalCount(totalcount);
			List<MerchantAddress> list = this.merchantAddressService
					.getNearestMerchantAddress(vo.getGoodsId(), vo.getLat(), vo
							.getLng());
			List<MerchantAddressVo> result = new ArrayList<MerchantAddressVo>();
			if (list != null && !list.isEmpty()) {
				for (MerchantAddress merchantAddress : list) {
					MerchantAddressVo addressVo = new MerchantAddressVo();
					addressVo.setSubMerchantName(merchantAddress
							.getSubMerchantName());
					addressVo.setLat(merchantAddress.getLat());
					addressVo.setLng(merchantAddress.getLng());
					addressVo.setDistance(merchantAddress.getDistance());
					addressVo.setAddress(merchantAddress.getExchangeAddress());
					addressVo.setPhoneNum(merchantAddress.getTelNo());
					result.add(addressVo);
				}
			}
			merResVo.setMerchantAddressList(result);
			return merResVo;
		} else {
			log.info("requestId:" + head.getRequestId()
					+ ",获取商品最近的三个商户时，报文解析异常。");
			throw new ServerDisponseException(TransmissionCode.ERROR_ADJUST
					.getCode(), TransmissionCode.ERROR_ADJUST.getMessage());
		}
	}

}
